124. 二叉树中的最大路径和
为保证权益,题目请参考 124. 二叉树中的最大路径和(From LeetCode).
解决方案1
CPP
C++
#include <iostream>
#include <climits>
#include <algorithm>
using namespace std;
struct TreeNode {
int val;
TreeNode *left;
TreeNode *right;
TreeNode(int x) : val(x), left(NULL), right(NULL) {}
};
class Solution {
private:
int maxs = INT_MIN;
public:
int maxPathSum(TreeNode *root) {
helper(root);
return this->maxs;
}
int helper(TreeNode *root) {
if (root) {
int l = helper(root->left);
int r = helper(root->right);
int tmp = root->val;
if(l <= 0){
if (r <= 0){
this->maxs = max(this->maxs, root->val);
return root->val;
}else{
this->maxs = max(this->maxs, root->val + r);
return root->val +r;
}
}else{
if(r <= 0){
this->maxs = max(this->maxs, root->val + l);
return root->val +l;
}else{
this->maxs = max(this->maxs, root->val + l + r);
return max(root->val + l, root->val + r);
}
}
}else {
return INT_MIN;
}
}
};
int main() {
cout << "ok" << endl;
return 0;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56